package com.css.apps.base.post.action;

import java.util.ArrayList;
import java.util.List;

import com.css.apps.base.user.model.SUser;
import com.css.apps.base.user.model.SUserPost;
import com.css.core.configuration.Environment;
import com.css.db.query.QueryCache;
import com.css.db.query.TransactionCache;
import com.css.util.Ajax;
import com.css.util.Messages;
import com.css.util.StringHelper;
import com.css.webbase.webwork.action.UserAction;

@SuppressWarnings("serial")
public class AddPostUser extends UserAction {

	private String postId;
	private String mulIds;
	
	@Override
	protected String userGo() {
		if (StringHelper.isAnyEmpty(postId, mulIds)) {
			result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.fieldEmpty"));
			return ERROR;
		}
		List<SUserPost> addList = new ArrayList<>();;
		List<String> userIds = StringHelper.strToList(mulIds);
		for (String userId : userIds) {
			String orgId = null;
			SUser user = QueryCache.get(SUser.class, userId);
			if (user != null) {
				orgId = user.getOrganId();
			}
			if (orgId != null) {
				SUserPost up = new SUserPost();
				up.setUserId(userId);
				up.setPostId(postId);
				up.setOrgId(orgId);
				addList.add(up);
			}
		}
		TransactionCache tx = null;
		try {
			tx = new TransactionCache();
			tx.save(addList);
			tx.commit();
			result = Ajax.JSONResult(Environment.RESULT_CODE_SUCCESS, Messages.getString("systemMsg.success"));
			return SUCCESS;
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();
			result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.exception"));
			return ERROR;
		}
	}

	public String getPostId() {
		return postId;
	}

	public void setPostId(String postId) {
		this.postId = postId;
	}

	public String getMulIds() {
		return mulIds;
	}

	public void setMulIds(String mulIds) {
		this.mulIds = mulIds;
	}
	
}
